import axios from 'axios'
import {Message} from 'element-ui'
import cookie from 'js-cookie'

// 创建axios实例
const service = axios.create({
    baseURL: 'http://localhost:9091', // api 的 base_url
    timeout: 1000000 // 请求超时时间
})

// http request 拦截器
service.interceptors.request.use(
    config => {
        // token 先不处理，后续使用时在完善
        if (cookie.get('adminToken')) {
            config.headers['token'] = cookie.get('adminToken')
        }
        return config
    },
    err => {
        return Promise.reject(err)
    })

// http response 拦截器
service.interceptors.response.use(
    response => {
        if (response.code === 208) {
            this.$message.warning(response.message)
            router.push('login')
            return
        } else {
            if (response.data.code === 200) {
                return response.data
            } else {
                Message({
                    message: response.data.message,
                    type: 'error',
                    duration: 5 * 1000
                })
                return Promise.reject(response.data)
            }
        }
    },
    error => {
        return Promise.reject(error.response)
    })

export default service
